package com.zjht.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartbit.kryojredis.JCache;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.zjht.account.common.merchant.model.Ticket;
import com.zjht.utils.MapCacheManager;

/**
 * @author Eirui
 *
 */
@Controller
public class RedisSynController {

    private static final Logger log             = LoggerFactory.getLogger(RedisSynController.class);

    private MapCacheManager     mapCacheManager = MapCacheManager.getInstance();
    
    @Resource
    private JCache              jCache;


    /**
     * Method updateTicketStatus
     * 
     * @param request Update Request
     * 
     * @param response update Response
     * 
     * @return String body
     */
    @RequestMapping(value = "updateTicketStatus", method = { RequestMethod.POST })
    public @ResponseBody String updateTicketStatus(HttpServletRequest request) {
        Map<String, Object> requestParameterMap = requestParameterToMap(request);
        Map<String, Object> responseMap = new HashMap<String, Object>();
        log.info("UpdateTicketStatus have request:[{}]", requestParameterMap);
        try {
            Ticket ticket = updateTicketStatusInRedis(requestParameterMap);
            updateTicketStatusInDataBase(ticket);
            log.info("Response success!");
            responseMap.put("code", "0000");
        } catch (Throwable t) {
            log.error("Response error!", t);
            responseMap.put("code", "9999");
        }
        return JSON.toJSONString(responseMap);
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private Map<String, Object> requestParameterToMap(HttpServletRequest request) {
        Map<String, Object> properties = request.getParameterMap();
        Map<String, Object> returnMap = new HashMap<String, Object>();
        Iterator<Entry<String, Object>> entries = properties.entrySet().iterator();
        Map.Entry entry;
        String keyName = "";
        String keyValue = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            keyName = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                keyValue = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    keyValue = values[i] + ",";
                }
                keyValue = keyValue.substring(0, keyValue.length() - 1);
            } else {
                keyValue = valueObj.toString();
            }
            returnMap.put(keyName, keyValue);
        }
        return returnMap;
    }

    private Ticket updateTicketStatusInRedis(Map<String, Object> requestParameterMap) throws Throwable {
        Ticket ticket = parameterToTicket(requestParameterMap);
        String assistCode = ticket.getAssisCode();
        //boolean isSetRedis = RedisClient.set(assistCode, ticket);
        String statusRedis = jCache.putObject(assistCode, ticket);
        log.info("AssistCode:[{}],update to Redis[{}]", assistCode,statusRedis);
        return ticket;
    }

    private Ticket parameterToTicket(Map<String, Object> ticketParameter) {
        return JSON.parseObject((String) ticketParameter.get("ticket"), Ticket.class);
    }

    private void updateTicketStatusInDataBase(Ticket ticket) throws Throwable {
        String assisCode = ticket.getAssisCode();
        mapCacheManager.putCache(assisCode, ticket);
        log.info("ThreadCacheMap have:[{}]pcs", mapCacheManager.getCacheSize());
    }
}
